from django.shortcuts import render, HttpResponse, redirect
# 认证模块
from django.contrib import auth
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.decorators import login_required
# 对应数据库
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password, check_password
from hashlib import md5
# Create your views here.

# m = md5()
# m.update(b'xxx')
# m.hexdigest()

# @login_required
def myindex(request):
    print(request.user)
    print(request.session)
    if request.user:
        return render(request, 'myindex.html', {"user": request.user})
    else:
        return redirect("mylogin")


@login_required
def mytest(request):
    return HttpResponse("这是一个需要登录才能看到的界面")


def register(request):
    if request.method == "GET":
        return render(request, 'regist.html')
    if request.method == "POST":
        username = request.POST.get("username", "")
        passwd = request.POST.get("passwd", "")
        User.objects.create(username=username, password=passwd)
        return redirect("index")


def mylogin(request):
    if request.method == "GET":
        return render(request, 'mylogin.html')
    if request.method == "POST":
        username = request.POST.get("username", "")
        passwd = request.POST.get("passwd", "")
        # print(username)
        # print(passwd)
        # user_obj = User.objects.get(username=username, password=passwd)
        user_obj = auth.authenticate(username=username, password=passwd)
        # print(user_obj)
        if user_obj:
            login(request, user_obj)
        return redirect("myindex")


def myloginout(request):
    logout(request)
    return redirect('mylogin')
